package com.uyaer.wheel.game
{
	import com.uyaer.wheel.common.Common;
	import com.uyaer.wheel.common.Config;
	import com.uyaer.wheel.events.EventType;
	import com.uyaer.wheel.res.ResManager;
	
	import flash.geom.Point;
	
	import starling.display.Image;
	import starling.display.Sprite;
	import starling.display.Stage;
	import starling.events.Event;
	import starling.textures.Texture;

	public class Background
	{
		private static var m_instance:Background;
		
		private var stage:Stage;
		private var con:Sprite;
		private var bg1:Image;
		private var bg2:Image;
		public function Background()
		{
		}
		
		public static function get instance():Background{
			return m_instance ||= new Background();
		}
		
		public function start(stage:Stage):void{
			this.stage = stage;
			var bgTexture:Texture = ResManager.me.getTexture("map_fill");
			bgTexture.repeat = true;
			var bg1:Image = new Image(bgTexture);
			var bg2:Image = new Image(bgTexture);
			bg1.width = bg2.width = Common.W;
			bg1.height = bg2.height = Common.H;
			bg1.setTexCoords(1,new Point(Common.W/bgTexture.width,0));
			bg1.setTexCoords(2,new Point(0,Common.H/bgTexture.height));
			bg1.setTexCoords(3,new Point(Common.W/bgTexture.width,Common.H/bgTexture.height));
			bg2.setTexCoords(1,new Point(Common.W/bgTexture.width,0));
			bg2.setTexCoords(2,new Point(0,Common.H/bgTexture.height));
			bg2.setTexCoords(3,new Point(Common.W/bgTexture.width,Common.H/bgTexture.height));
			
			bg2.y = - Common.H;
			con = new Sprite();
			con.addChild(bg1);
			con.addChild(bg2);
			stage.addChildAt(con,0);
			if(Config.isUp){
				con.y = 0;
			}else{
				con.y = Common.H;
			}
			
			stage.addEventListener(EventType.MAP_MOVE,onMapMove);
		}
		
		private function onMapMove(e:Event):void{
			var d:Number = e.data as Number;
			if(Config.isUp){
				con.y += d;
				if(con.y >= Common.H){
					con.y -= Common.H;
				}
			}else{
				con.y -= d;
				if(con.y <= 0){
					con.y += Common.H;
				}
			}
		}
		
		public function destory():void{
			stage.removeEventListener(EventType.MAP_MOVE,onMapMove);
			con.removeChildren(0,-1,true);
		}
	}
}